package th.retrofit.lib;

import java.util.Arrays;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;

public class Solution56 {

    public int[][] merge(int[][] intervals) {
        List<int[]> results = new LinkedList<>();
        Arrays.sort(intervals, (o1, o2) -> o1[0] - o2[0]);
        results.add(intervals[0]);
        for (int i = 1; i < intervals.length; i++) {
            int[] first = results.get(results.size() - 1);
            int[] second = intervals[i];
            if (second[0] <= first[1]) {
                results.set(results.size() - 1, new int[]{first[0], Math.max(first[1], second[1])});
            } else {
                results.add(second);
            }
        }
        int[][] arr = new int[results.size()][2];
        return results.toArray(arr);
    }


    public static void main(String[] args) {
        int[][] intervals = new int[][]{{2,6},{1,3},{8,10},{15,18}};
        intervals = new Solution56().merge(intervals);
        for (int i = 0; i < intervals.length; i++) {
            for (int j = 0; j < 2; j++) {
                System.out.print(intervals[i][j]);
                System.out.print(", ");
            }
            System.out.println();
        }
    }
}
